define(["jquery","template","bbcare","comm/form/form.attention","comm/form/form.validate"],function($,template,$bb,$attention,$validate){
	var quest = {};

	/**
	 * 数据处理(若不需要数据处理，可以不写)
	 */
    quest.formatData = function(obj){
    	if( typeof obj.inParams != "string" ) obj.inParams = JSON.stringify(obj.inParams);
    	if( typeof obj.outParams != "string" ) obj.outParams = JSON.stringify(obj.outParams);
		return obj;
	}

	/**
	 * tpl模板
	 */
	quest.tpl = function(){
		return 	'<script id="tpl_question_dynamicSelect" type="text/html">'+
				'	<div {{if relationId}}relationId="{{relationId}}"{{/if}} class="qaCard-dynamicSelect qaCard form-group form-group-sm col-sm-{{length}} col-md-{{length}} grid-label-{{labelLength}}">'+
				'		<label class="control-label {{align}}">{{label}}</label>'+
				'   	<div class="control-input">'+
				'			{{if status=="default"}}'+
				'				<select class="form-control validatebox" name="{{name}}" data-url="{{url}}" data-baseUrl="{{baseUrl}}" data-inParams="{{inParams}}" data-outParams="{{outParams}}" data-type="{{type}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" data-validate="{{validate}}" data-attention="{{attention}}">'+
				'				</select>'+
				'			{{else if status=="readonly"}}'+
				'				<p class="form-control-static validatebox" name="{{name}}" data-url="{{url}}" data-baseUrl="{{baseUrl}}" data-inParams="{{inParams}}" data-outParams="{{outParams}}" data-type="{{type}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" data-validate="{{validate}}" data-attention="{{attention}}"></p>'+
				'			{{else if status=="disabled"}}'+
				'				<select class="form-control validatebox" name="{{name}}" data-url="{{url}}" data-baseUrl="{{baseUrl}}" data-inParams="{{inParams}}" data-outParams="{{outParams}}" data-type="{{type}}" data-innDeCode="{{innDeCode}}" data-deCode="{{deCode}}" data-dataUnit="{{dataUnit}}" data-validate="{{validate}}" data-attention="{{attention}}" disabled>'+
				'				</select>'+
				'			{{/if}}'+
				'  		</div>'+
				'	</div>'+
				'</script>';
	}

	/**
	 * 赋值
	 */
	quest.setValue = function($dom,value){
		if( value ){
			setTimeout(function(){
				if( $dom.hasClass("form-control-static") ){
					var list = JSON.parse( $dom.attr("data-list") );
					for (var i = 0; i < list.length; i++) {
						if( list[i].key == value.quesValue ){
							$dom.html( list[i].text );
							break;
						}
					}
				}else{
					$dom.val(value.quesValue);
				}
			},500);
		}
	}

	/**
	 * 获取value（保存时，获取每个dom对应的答案）
	 */
	quest.getValue = function($dom,name){
		var value = {};
		if( $dom.hasClass("form-control-static") ){
			var list = JSON.parse( $dom.attr("data-list") );
			for (var i = 0; i < list.length; i++) {
				if( list[i].text == $dom.html() ){
					var val = list[i].key;
					break;
				} 
			}
		}else{
			var val = $dom.val();
		}
		value.quesValue = val;
		value.deCode = $dom.attr("data-deCode");
		value.innDeCode = $dom.attr("data-innDeCode");
		var dataUnit = $dom.attr("data-dataUnit");
		if( dataUnit ) value.dataUnit = dataUnit;
		return value;
	}

	/**
	 * 事件(若没有事件函数，可以不写)
	 * 		需要用到eventParams参数里的两个参数userId、gender、calcTestTime
	 */
	quest.event = function(eventParams,id){
		var $domAll = $("#" + id + " .qaCard-dynamicSelect");
		$domAll.each(function(i){
			var $dom = $(this).find(".validatebox");
			var obj = {};
			obj.dom = $dom;
			obj.url = $dom.attr("data-url");
			obj.baseUrl = $dom.attr("data-baseUrl");
			obj.inParams = JSON.parse($dom.attr("data-inParams"));
			obj.outParams = JSON.parse($dom.attr("data-outParams"));
			if( obj.url ) ajaxList(obj,ajaxListCallBack);
		});
	}

	/**
	 * 提醒
	 */
	quest.attention = function(id){
        $("#" + id + " .qaCard-dynamicSelect .validatebox").bind("change",onAttention);
        // 初始化
        $("#" + id + " .qaCard-dynamicSelect .validatebox").change();
	}

	/**
	 * 校验
	 * flag:
	 * 	 true:  (点击保存按钮时使用)
	 * 	 false: 
	 */
	quest.validate = function(id,flag){
        $("#" + id + " .qaCard-dynamicSelect .validatebox").bind("change",onValidate);
        if( flag ){
        	var result = true;
        	$("#" + id + " .qaCard-dynamicSelect .validatebox").each(function(i){
        		var params = {
		            "value":getValue($(this)),
		            "dom":$(this),
		            "flag":flag,
		        };
				var success = $validate.init(params,handleByRuleValidate,handleBytypeValidate);
	            result = result && success;
	            if( !result ) return result;
	    	});
        	return result;
        }
	}

	/********************  event begin  ********************/

	/**
	 * option的tpl
	 */
	var tplOption = function(){
		return  '<script id="tpl_dynamicSelect_option" type="text/html">'+
				'	{{each list as item i}}'+
				'   	<option value="{{item.key}}">{{item.text}}</option>'+
				'	{{/each}}'+
				'</script>';
	}

	/**
	 * option的ui
	 */
	var uiOption = function(options){
		options.dom.html(tplOption());
        var h = template("tpl_dynamicSelect_option", options);;
        options.dom.html(h);
	}

	/**
	 * 查询成功后的回调函数
	 */
	var ajaxListCallBack = function(data,obj){
		var list = data[obj.outParams.data];
		obj.list = [];
		if( list.length > 0 ){
			for (var i = 0; i < list.length; i++) {
				obj.list[i] = {};
				if( typeof list[i] == "string" ){
    				obj.list[i].key = list[i];
    				obj.list[i].text = list[i];
				}else{
    				obj.list[i].key = list[i][obj.outParams.key];
    				obj.list[i].text = list[i][obj.outParams.text];
				}
			}
		}
		if( obj.dom.hasClass("form-control") ){
			uiOption(obj);
		}else if( obj.dom.hasClass("form-control-static") ){
			var listStr = JSON.stringify(obj.list);
			obj.dom.attr("data-list",listStr);
		}
	}

	/**
	 * 查询
	 */
	var ajaxList = function(obj,callback){
		var projectName = obj.baseUrl ? obj.baseUrl : "followapp";
    	var URL = $bb.baseUrl(projectName);
		$bb.ajax({
			url: URL + obj.url,
			data:JSON.stringify({
				data : obj.inParams
			}),
			success: function(data){
				if(data.success){
					callback(data.data,obj);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询出错！");
				}
			}
		});
	}

	/********************  event end  ********************/

	/**
	 * 获取输入的值(validate、attention中需要用到)
	 */
	var getValue = function($dom){
		var value = $dom.hasClass("form-control-static") ? $dom.html() : $dom.val();
		return value;
	}

	/********************  attention begin  ********************/

	/**
	 * xx情况下触发的事件 (有可能是失去焦点等)
	 */
	var onAttention = function(){
		var params = {
            "value":getValue($(this)),
            "dom":$(this),
        };
		$attention.init(params,handleByRule,handleBytype);
    }

    /**
     * 根据单个规则rule获取单个规则的结果result
     * 该题型已有规则在case里拦截，公用规则从default里返回结果
     * @return Boolean [布尔值]
     */
    var handleByRule = function(obj){
    	var result;
    	switch(obj.type) {
            default:
            	result = $attention.handleByRule(obj);
        }
        return result;
    }

    /**
     * 根据提醒类型(type)执行对应的方法
     * 该题型已有提醒类型在case里拦截，公用提醒类型在default里处理
     */
    var handleBytype = function(obj){
    	if( obj.type ){
    		switch(obj.type) {
	            default:
            		$attention.handleBytype(obj);
	        }
    	}
    }

    /********************  attention end  ********************/

    /********************  validate begin  ********************/

    /**
	 * xx情况下触发的事件 (有可能是失去焦点等)
	 */
	var onValidate = function(){
		var params = {
            "value":getValue($(this)),
            "dom":$(this),
        };
		$validate.init(params,handleByRuleValidate,handleBytypeValidate);
	}

	/**
     * 根据单个规则rule获取单个规则的结果result
     * 该题型已有规则在case里拦截，公用规则从default里返回结果
     * @return Boolean [布尔值]
     */
    var handleByRuleValidate = function(obj){
    	var result = true;
    	switch(obj.type) {
            default:
            	result = $validate.handleByRule(obj);
        }
        return result;
    }

    /**
     * 根据提醒类型(type)执行对应的方法
     * 该题型已有提醒类型在case里拦截，公用提醒类型在default里处理
     */
    var handleBytypeValidate = function(obj){
    	if( obj.type ){
    		switch(obj.type) {
	            default:
            		$validate.handleBytype(obj);
	        }
    	}
    }

	/********************  validate begin  ********************/
    
	return quest;
});